<?php
namespace backend\controllers;

use Yii;
use yii\web\AdminController;
use backend\models\CouponReceive;
use common\models\Coupon;
use backend\models\CouponPlus;
use PHPExcel;
use backend\models\GoodsSaleEdit;
use common\helps\tools;

class CouponController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'Coupon';
    
    public function actionList(){
        return $this->render('list');
    }
    
    public function actionCouponList(){
        $data = Yii::$app->request->post();
        $query = Coupon::find()->where('1=1');
        if ($data['type']){
            $query = $query->andWhere('type=:type',[':type'=>$data['type']]);
        }
        if ($data['title']){
            $query = $query->andWhere(['like','title',$data['title']]);
        }
        $query = $query->orderBy('use_flg desc');
        $count = $query->count();
        $list = $query->offset($data['start'])->limit($data['length'])->asArray()->all();
        $result_val = [];
        if (is_array($list) && count($list) > 0) foreach ($list as $list_val){
            $coupon_time = date('Y-m-d',strtotime($list_val['coupon_start_time'])).' - '.date('Y-m-d',strtotime($list_val['coupon_end_time']));
            $use_mark = explode(',', $list_val['use_mark']);
            $use_mark_arr = [];
            if (is_array($use_mark) && count($use_mark) > 0)foreach ($use_mark as $use_mark_val){
                $use_mark_arr[] = $GLOBALS['_COUPON_USE_MARK'][$use_mark_val];
            }
            $result_val[] = [
                'id'=>$list_val['id'],
                'type'=>$GLOBALS['_COUPON_TYPE'][$list_val['type']],
                'title'=>$list_val['title'],
                'highlight'=>$list_val['highlight'],
                'coupon_time'=>$coupon_time,
                'release_number'=>$list_val['release_number'],
                'draw_count'=>$list_val['draw_count'],
                'use_mark'=>implode('、', $use_mark_arr),
                'use_flg'=>$list_val['use_flg']
            ];
        }
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $result_val;
        return \yii\helpers\Json::encode($result);
    }
    
    //优惠券启用禁用
    public function actionChangeCouponStatus()
    {
        $data_now = array();
        $model = new Coupon();
        $data = Yii::$app->request->post();
        $use_flg = $data['use_flg'];
        $data_now['use_flg'] = $use_flg;
        $data_now['editor'] = $model->getCreator();
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $coupon_where = ['id'=>$data['id']];
        $ret = $model::updateAll($data_now,$coupon_where);
        if(!$ret){
            throw new \Exception('操作失败');
        }
        $this->retJson('操作成功',200);
    }
    
    //优惠卷详情信息
    public function actionCouponDetail(){
        $data = Yii::$app->request->post();
        $result = Coupon::find()->where('id=:id',[':id'=>$data['id']])->asArray()->one();
        $use_mark = explode(',', $result['use_mark']);
        $result['use_mark'] = $use_mark;
        $detail = CouponPlus::find()->where('coupon_id=:coupon_id',[':coupon_id'=>$data['id']])->orderBy('sort asc')->asArray()->all();
        $result['plus'] = $detail;
        $this->retJson($result,200);
    }
    
    //导入优惠卷对应的商品
    public function actionExcelFileUpload(){
        try {
            if (count ( $_FILES ) == 0) {
                throw new \Exception('未上传文件');
            }
            $fileElementName = array_keys ( $_FILES );
            $fileElementName = $fileElementName [0];
            
            if (! $_FILES [$fileElementName]){
                throw new \Exception('未上传文件');
            }
            $file = $_FILES [$fileElementName];
            if($_FILES[$fileElementName]['size'] > 2097152) {//文件不能超过2M
                throw new \Exception('文件大小超过2M');
            }
            // 验证文件类型
            $lastdot = strrpos ( $file ['name'], "." ); // 找到区分文件名与扩展名的标记符“.”最后出现的位置
            $reader_type = substr ( $file ['name'], $lastdot + 1 ); // 取出扩展名
            $allowType = array ('xls','xlsx');
            if (! in_array ( strtolower ( $reader_type ), $allowType )) {
                throw new \Exception('只支持xls,xlsx文件');
            }
            $extend = ($reader_type == 'xlsx' ? 'Excel2007' : 'Excel5');
            set_time_limit(0);
            $excel = new PHPExcel();
            $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
            $cacheSettings = array();
            \PHPExcel_Settings::setCacheStorageMethod($cacheMethod,$cacheSettings);
            $objReader = \PHPExcel_IOFactory::createReader($extend);
            $objPHPExcel = $objReader->load($file ['tmp_name']);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
            if($highestRow < 2){
                throw new \Exception('上传文件数据不能为空');
            }
            if($highestRow > 1001){
                throw new \Exception('上传文件数据超过行数限制,最大不能超过一千条');
            }
            
            $highestColumn = $objWorksheet->getHighestColumn();// 取得总列数
            $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString ( $highestColumn ); // 总列数
            $dataKey = array();
            //商品导入标题对应键
            $excelTitle = array('sku'=>'SKU（物料号）');
            $dataKey = array_keys($excelTitle);
            $title = array_values($excelTitle);
            //获取数据集合
            $excelDataBefore = $excelData = $fileTitle = $data_arr =  array();
            for ($r = 1; $r <= $highestRow ;$r++){
                for($c = 0; $c < $highestColumnIndex; $c ++) {
                    $getCellByColumnAndRowResult = trim ( $objWorksheet->getCellByColumnAndRow ( $c, $r )->getValue () );
                    if($r == 1){
                        $fileTitle [] = $getCellByColumnAndRowResult;
                    }else if(array_key_exists($c, $dataKey)){
                        $excelDataBefore[][$dataKey[$c]] = $excelData[][$dataKey[$c]] =  $getCellByColumnAndRowResult;
                    }
                }
            }
            if(count($excelData) == 0) throw new \Exception('未解析到可用数据');
            $fieldsTitle=array();
            $i = 2;
            foreach ($title as $k =>$v){
                if($v !== $fileTitle[$k]){
                    throw new \Exception('上传文件标题('.$fileTitle[$k].')格式不正确,应为'.$v);
                }
            }
            return $this->retJson($excelData,200);
        } catch (\Exception $e) {
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            return $this->retJson($e->getMessage(),500);
        }
    }
    
    public function actionValidateSku(){
        $data = Yii::$app->request->post();
        $sku = $data['sku'];
        if (!$sku) return false;
        $goods_sale = GoodsSaleEdit::find()->select('goods_name_cn')->where('sku=:sku',[':sku'=>$sku])->asArray()->one();
        if ($goods_sale['goods_name_cn']) {
            $this->retJson($goods_sale['goods_name_cn'],200);
        }
    }
    
    public function actionChangeCoupon(){
        $model = new Coupon();
        $data = Yii::$app->request->post();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $id = $data['coupon_id'];
            $oper = $model->getCreator();
            $oper_time = date('Y-m-d H:i:s');
            $type = $data['type'];
            $title = $data['title'];
            $highlight = $data['highlight'];
            $reservationtime = $data['reservationtime'];
            $time_a = explode(' - ', $reservationtime);
            $coupon_start_time = $time_a[0];
            $coupon_end_time = $time_a[1];
            if (!$coupon_start_time || !$coupon_end_time){
                throw new \Exception('时间格式错误，请重新选择优惠券有效日期段');
            }
            $content = $data['content'];
            $release_number = $data['release_number'];
            $use_mark = $data['use_mark_arr'];
            $use_flg = $data['use_flg'];
            $plus_1 = tools::arrayHasValue($data,'coupon_plus_1') ? $data['coupon_plus_1'] : [];
            $plus_2 = tools::arrayHasValue($data,'coupon_plus_2') ? $data['coupon_plus_2'] : [];
            $sku = tools::arrayHasValue($data,'sku') ? $data['sku'] : [];
            $category = tools::arrayHasValue($data,'category') ? $data['category'] : [];
            if (is_array($category) && count($category) > 0) {
                if (count($category) != count(array_unique($category))) {
                    throw new \Exception('分类名称选项不可重复，请检查后重新选择');
                }
            }
            if (is_array($sku) && count($sku) > 0) {
                if (count($sku) != count(array_unique($sku))){
                    throw new \Exception('物料号不可重复，请检查后重新填写');
                }
            }
            if (count($sku) == 0 && count($category) == 0){
                throw new \Exception('请选择至少填写一个活动分类或商品');
            }
            if (count($sku) > 0){
                $sale_sku = GoodsSaleEdit::find()->select('sku,goods_name_cn,goods_id')->where(['in','sku',$sku])->asArray()->all();
                if (count($sale_sku) != count($sku)) {
                    throw new \Exception('有填写的物料号不存在');
                }
                $sale_sku = array_combine(array_column($sale_sku, 'sku'),$sale_sku);
            }
            $plus_ids_1 = $plus_ids_2 = [];
            if ($id){
                $model = Coupon::findOne($id);
                $where_plus = ['coupon_id'=>$id];
                $plus_category = CouponPlus::find()->where($where_plus+['type'=>2])->asArray()->all();
                $plus_sku = CouponPlus::find()->where($where_plus+['type'=>1])->asArray()->all();
                $plus_ids_1 = array_column($plus_category, 'id');
                $plus_ids_2 = array_column($plus_sku, 'id');
                $model->editor = $oper;
                $model->edit_time = $oper_time;
            }else{
                $model->creator = $oper;
                $model->create_time = $oper_time;
            }
            $model->type = $type;
            $model->title = $title;
            $model->highlight = $highlight;
            $model->coupon_start_time = $coupon_start_time;
            $model->coupon_end_time = $coupon_end_time;
            $model->content = $content;
            $model->release_number = $release_number;
            $model->use_mark = $use_mark;
            $model->use_flg = $use_flg;
            $model->save();
            $id = $model->attributes['id'];
            if (!$id){
                throw new \Exception('操作失败，请重试');
            }
            $sort = $sort1 = 1;
            if (is_array($plus_1) && count($plus_1) > 0)for ($i=0;$i<count($plus_1);$i++){
                if (!$category[$i] && $category[$i] !== '0') continue;
                $plus = new CouponPlus();
                if ($plus_1[$i]){
                    $plus = $plus->findOne($plus_1[$i]);
                    $plus->editor = $oper;
                    $plus->edit_time = $oper_time;
                }else{
                    $plus->creator = $oper;
                    $plus->create_time = $oper_time;
                    $plus->type = 2;
                }
                $plus->coupon_id = $id;
                $plus->category_id = $category[$i];
                $plus->sort = $sort;
                $plus->save();
                $plus_id = $plus->attributes['id'];
                if (!$plus_id){
                    throw new \Exception('商品分类添加失败');
                }
                $sort++;
            }
            if (is_array($plus_2) && count($plus_2) > 0){
                for ($j=0;$j<count($plus_2);$j++){
                    if (!$sku[$j]) continue;
                    $plus = new CouponPlus();
                    if ($plus_2[$j]){
                        $plus = $plus->findOne($plus_2[$j]);
                        $plus->editor = $oper;
                        $plus->edit_time = $oper_time;
                    }else{
                        $plus->creator = $oper;
                        $plus->create_time = $oper_time;
                        $plus->type = 1;
                    }
                    $plus->coupon_id = $id;
                    $plus->sku = $sku[$j];
                    $plus->goods_name_cn = $sale_sku[$sku[$j]]['goods_name_cn'];
                    $plus->goods_id = $sale_sku[$sku[$j]]['goods_id'];
                    $plus->sort = $sort1;
                    $plus->save();
                    $plus_id = $plus->attributes['id'];
                    if (!$plus_id){
                        throw new \Exception('商品分类添加失败');
                    }
                    $sort1++;
                }
            }
            if (is_array($plus_ids_1) && count($plus_ids_1))foreach ($plus_ids_1 as $ids_1){
                if (!in_array($ids_1,$plus_1)){
                    $del = CouponPlus::deleteAll(['id'=>$ids_1]);
                    if(!$del){
                        throw new \Exception('操作失败');
                    }
                }
            }
            if (is_array($plus_ids_2) && count($plus_ids_2))foreach ($plus_ids_2 as $ids_2){
                if (!in_array($ids_2,$plus_2)){
                    $del = CouponPlus::deleteAll(['id'=>$ids_2]);
                    if(!$del){
                        throw new \Exception('操作失败');
                    }
                }
            }
            $transaction->commit();
            $this->retJson('编辑成功',200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }
    
    
    public function actionIndex()
    {
        return $this->render('index');
    }
    
    public function actionGetCoupon(){
        $data = Yii::$app->request->post();
        $query = CouponReceive::find()->where('1=1');
        if ($data['mobile']){
            $query = $query->andWhere('mobile=:mobile',[':mobile'=>$data['mobile']]);
        }
        if ($data['sms_verification']){
            $query = $query->andWhere('sms_verification=:sms_verification',[':sms_verification'=>$data['sms_verification']]);
        }
        if (!empty($data['is_exchange']) || $data['is_exchange'] === '0'){
            $query = $query->andWhere('is_exchange=:is_exchange',[':is_exchange'=>$data['is_exchange']]);
        }
        $query = $query->orderBy('use_flg desc,mobile desc');
        $count = $query->count();
        $list = $query->offset($data['start'])->limit($data['length'])->asArray()->all();
        $result_val = [];
        if (is_array($list) && count($list) > 0) foreach ($list as $list_val){
            $coupon_time = date('Y-m',strtotime($list_val['coupon_start_time'])).' - '.date('Y-m',strtotime($list_val['coupon_end_time']));
            $result_val[] = [
                'id'=>$list_val['id'],
                'title'=>$list_val['title'],
                'coupon_time'=>$coupon_time,
                'is_exchange'=>$list_val['is_exchange']
            ];
        }
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $result_val;
        return \yii\helpers\Json::encode($result);
    }
    
    public function actionGetGrantCoupon(){
        $data = Yii::$app->request->post();
        if (!$data['mobile'] || !$data['sms_verification']){
            $this->retJson('暂无需发放的优惠券',500);
        }
        $query = CouponReceive::find()->where(
            'mobile=:mobile and sms_verification=:sms_verification',[':mobile'=>$data['mobile'],':sms_verification'=>$data['sms_verification']]
        );
        $query = $query->orderBy('use_flg desc');
        $list = $query->asArray()->all();
        $result_val = [];
        if (is_array($list) && count($list) > 0) foreach ($list as $list_val){
            if ($list_val['is_exchange'] == 1){
                $this->retJson('您输入的短信验证码对应的优惠券已经被发放，请确认',500);
            }
            $coupon_time = date('Y-m',strtotime($list_val['coupon_start_time'])).' - '.date('Y-m',strtotime($list_val['coupon_end_time']));
            $result_val[] = [
                'id'=>$list_val['id'],
                'title'=>$list_val['title'],
                'coupon_time'=>$coupon_time,
                'is_exchange'=>$list_val['is_exchange']
            ];
        }else{
            $this->retJson('无优惠券，请确认您的手机号和验证码',500);
        }
        $this->retJson($result_val,200);
    }
    
    public function actionGrantCoupon(){
        $grant_coupon = new CouponReceive();
        $data = Yii::$app->request->post();
        $query = CouponReceive::find()->select('id')->where('is_exchange=0');
        if ($data['mobile']){
            $query = $query->andWhere('mobile=:mobile',[':mobile'=>$data['mobile']]);
        }
        if ($data['sms_verification']){
            $query = $query->andWhere('sms_verification=:sms_verification',[':sms_verification'=>$data['sms_verification']]);
        }
        $query = $query->orderBy('use_flg desc,mobile desc');
        $list = $query->asArray()->all();
        if (count($list) == 0){
            $this->retJson('暂无需发放的优惠券',500);
        }
        $coupon_id = array_column($list, 'id');
        $set = ['is_exchange'=>1,'exchange_time'=>date('Y-m-d H:i:s'),'exchangor'=>$grant_coupon->getCreator()];
        $ret = $grant_coupon->updateAll($set,['id'=>$coupon_id]);
        if(!$ret){
            $this->retJson('发放优惠券失败，请重新操作',500);
        }
        $this->retJson('操作成功',200);
    }
    
    public function actionReport(){
        return $this->render('report');
    }
    
    public function actionCouponReport(){
        $data = Yii::$app->request->post();
        $sql = 'SELECT id,type,coupon_id,title,mobile,receive_time,exchange_time,use_mark,is_exchange FROM j_coupon_receive WHERE 1=1';
        $where = [];
        if($data['type']){
            $sql .= ' AND type=:type';
            $where[':type'] = $data['type'];
        }
        if($data['coupon_id']){
            $sql .= ' AND coupon_id=:coupon_id';
            $where[':coupon_id'] = $data['coupon_id'];
        }
        if($data['title']){
            $sql .= ' AND title like "'.$data['title'].'"';
        }
        if($data['is_exchange'] || $data['is_exchange'] == '0'){
            $sql .= ' AND is_exchange=:is_exchange';
            $where[':is_exchange'] = $data['is_exchange'];
        }
        if($data['receive_time'] && $data['exchange_time']){
            $receive_time = explode(' - ', $data['receive_time']);
            $exchange_time = explode(' - ', $data['exchange_time']);
            if (count($receive_time) == 2 || count($exchange_time) == 2){
                $sql .= ' AND ((receive_time between "'.$receive_time[0].'" and "'.$receive_time[1].'") or (exchange_time between "'.$exchange_time[0].'" and "'.$exchange_time[1].'"))';
            }
        }elseif ($data['receive_time'] || $data['exchange_time']){
            $receive_time = explode(' - ', $data['receive_time']);
            $exchange_time = explode(' - ', $data['exchange_time']);
            if (count($receive_time) == 2){
                $sql .= ' AND (receive_time between "'.$receive_time[0].'" and "'.$receive_time[1].'")';
            }elseif (count($exchange_time) == 2){
                $sql .= ' AND (exchange_time between "'.$exchange_time[0].'" and "'.$exchange_time[1].'")';
            }
        }
        $couponRe = CouponReceive::findBySql($sql,$where);
        if (tools::arrayHasValue($data,'is_export')){
            if (!$data['search_count']){
                $couponRe = [];
            }else{
                $couponRe = $couponRe->asArray()->all();
            }
            
            $filed = [
                'id'=>'序号',
                'type'=>'优惠券类型',
                'coupon_id'=>'优惠券ID',
                'title'=>'优惠券名称',
                'mobile'=>'手机号',
                'receive_time'=>'领取时间',
                'exchange_time'=>'兑换时间',
                'use_mark'=>'领取来源',
                'is_exchange'=>'兑换状态'
            ];
            $list = [];
            if (is_array($couponRe) && count($couponRe) > 0)foreach ($couponRe as $coupon_val){
                $coupon_val['type'] = $GLOBALS['_COUPON_TYPE'][$coupon_val['type']];
                $coupon_val['use_mark'] = $GLOBALS['_COUPON_USE_MARK'][$coupon_val['use_mark']];
                $coupon_val['is_exchange'] = $GLOBALS['_COUPON_EXCHANGE_STATUS'][$coupon_val['is_exchange']];
                $list[] = $coupon_val;
            }
            $filename = 'coupon_report_'.date('YmdHis').'.xls';
            $filename = iconv("utf-8", "gb2312", $filename);
            tools::exportExcel($filed, $list, $filename);
        }else{
            $count = $couponRe->count();
            $couponRe = $couponRe->offset($data['start'])->limit($data['length'])->asArray()->all();
        }
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $couponRe;
        return \yii\helpers\Json::encode($result);
    }
}